<!-- 邮件任务 -->
<template>
  <div  class="dashboard-editor-container">
    <el-row style="background: #fff; padding: 16px 16px; margin-bottom: 32px">
      <div style="display:flex;justify-content:space-between;">
        <div class="title">邮件通知任务</div>
        <div >
          <el-button type="primary" icon='el-icon-circle-plus-outline' @click="addResources()">添加任务</el-button>
          <el-button type="warning" icon='el-icon-refresh' @click="refreshPage()">刷新页面</el-button>
        </div>
      </div>
        <el-table class="tableRowclcick" border :data="tableData" style="width: 100%; margin-top: 15px" @row-click="rowclick" :row-class-name="rowClassName" :row-style="rowStyle" :stripe="false">
          <el-table-column label="序号"  width="60" type="index" :index='(index)=>{return (index + 1) + (this.pageNum - 1)*this.pageSize}'> </el-table-column>
          <el-table-column label="任务ID" width="120" prop="TaskID" align="left"></el-table-column>
          <el-table-column label="邮件标题" width="220" prop="Title" align="left"></el-table-column>
          <el-table-column label="状态" align="left" width="120px">
            <template slot-scope="scope">
              <p style="color:#909399" size="small" v-if="scope.row.ExecStatus === 0" type="info">等待执行</p>
              <p style="color:#67C23A" size="small" v-if="scope.row.ExecStatus === 1" type="success">执行完成</p>
              <p style="color:#409EFF" size="small" v-if="scope.row.ExecStatus === 2" type="danger">正在执行</p>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="CreateTime" align="left" width="200px"></el-table-column>
          <el-table-column label="执行耗时" prop="StartTime" align="left" show-overflow-tooltip></el-table-column>
          <el-table-column label="执行结果" align="left" width="280px" show-overflow-tooltip>
            <template slot-scope="scope">
              <span style="margin-right: 10px;color:#67C23A">成功({{scope.row.success}})</span>
              <span style="margin-right: 10px;color:#F56C6C">失败({{scope.row.danger}})</span>
              <span style="margin-right: 10px;color:#909399">等待({{scope.row.info}})</span>
              <span style="margin-right: 10px;color:#409EFF">已阅({{scope.row.read}})</span>
            </template>
          </el-table-column>
          <el-table-column label="附件数量" prop="Attachlength" align="left" width="100px"></el-table-column>
          <el-table-column label="操作" align="left" width="150px" fixed="right">
            <template slot-scope="scope">
              <!-- <el-button size="mini" @click="changeMailGlobal(scope.row)">修改</el-button> -->
              <el-button size="mini" @click="changeMailGlobal(scope.row)">查看</el-button>
              <el-button size="mini" type="danger" @click="deleteMailGlobal(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination 
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" 
          :current-page=pageNum
          :page-size=pageSize
          background 
          layout="total, prev, pager, sizes, next, jumper"
          :total="total">
        </el-pagination>
        <div class="title"  style="width: 100%; margin-top: 15px">任务执行详情<div v-show="TaskID !== ''" style="margin-left:20px">任务ID: {{TaskID}}</div></div>
        <el-table stripe border :data="ToAccount" style="width: 100%; margin-top: 15px" height="500">
          <el-table-column label="序号"  width="60" type="index" :index='(index)=>{return (index + 1) + (this.pageNum - 1)*this.pageSize}'> </el-table-column>
          <el-table-column label="收件人" width="350" prop="Name" align="left" show-overflow-tooltip></el-table-column>
          <el-table-column label="邮箱" width="220" prop="Account" align="left"></el-table-column>
          <el-table-column label="邮件跟踪" align="left" width="120px">
            <template slot-scope="scope">
              <p style="color:#67C23A" size="small" v-if="scope.row.ExecStatus === 1" type="success">送达</p>
              <p style="color:#F56C6C" size="small" v-if="scope.row.ExecStatus === 2" type="danger">失败</p>
              <p style="color:#909399" size="small" v-if="scope.row.ExecStatus === 0" type="info">等待</p>
              <p style="color:#409EFF" size="small" v-if="scope.row.ExecStatus === 3">已阅</p>
            </template>
          </el-table-column>
          <el-table-column label="地址(IP)" width="220" prop="RcvIP" align="left"></el-table-column>
          <el-table-column label="地址解析"  prop="RcvArea" align="left"></el-table-column>
          <el-table-column label="阅读时间"  prop="StatusChangeTime" align="left"></el-table-column>
          <!-- <el-table-column></el-table-column> -->
        </el-table>
    </el-row>
    <el-dialog
      :close-on-press-escape=false
      top="5vh"
      :title="Action === 1 ? '添加邮件通知任务' : '查看邮件通知任务' "
      :visible.sync="dialogVisible"
      v-el-drag-dialog
      :close-on-click-modal = false
      width="60%">
      <el-form label-width="120px" :model="resourceForm" :rules="rules" ref="resourceForm">
        <el-form-item label='邮件接收对象:' prop="Name">
          <el-input v-model="resourceForm.Name" @focus="Action === 1 ? transferdialog = true : ''">选择对象</el-input>
          <!-- <el-select v-model="resourceForm.Name" value-key="EMail" multiple placeholder="请选择" style="width:100%;" @clcik="transferdialog = true" disabled>
            <el-option
              v-for="item in choseman"
              :key="item.EMail"
              :label="item.Name"
              :value="item">
              <span style="float: left">{{ item.Name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px;margin-right:20px">{{ item.EMail }}</span>
            </el-option>
          </el-select> -->
        </el-form-item>
        <el-form-item label='邮件标题:' prop="Title">
          <el-input v-model="resourceForm.Title"></el-input>
        </el-form-item>
        <!-- <el-form-item label='图片跳转链接:' prop="link" v-show="Action !== 2">
          <el-input v-model="resourceForm.link"></el-input>
        </el-form-item> -->
        <el-form-item label='邮件内容:' prop="Subject">
          <el-tabs type="border-card" class="tabs">
            <el-tab-pane label="编辑邮件">
              <editor-bar
                :value="editorhtml"
                :link="resourceForm.link"
                v-model="resourceForm.Subject"
                @change="editorchange"
                @fileclick="fileclick"
                @imgdialogopen="imgdialogopen"
                @delimiter="delimiter"
                @aiSoftText="aiSoftText"
                :rows="2"
                ref="editor"
              ></editor-bar>
              <input style="display:none" type="file" ref="filetemplete" @change="filetempleteChange($event)" accept=".html,.txt">
            </el-tab-pane>
            <!-- <el-tab-pane label="自定义邮件">
              <el-button @click="$refs.filetemplete.click()">邮件上传</el-button>
            </el-tab-pane> -->
            <el-tab-pane label="查看源码">
              <el-input
                type="textarea"
                :rows="18"
                @blur="changesourceCode()"
                placeholder="请输入内容"
                v-model="sethtml">
              </el-input>
            </el-tab-pane>
          </el-tabs>
        </el-form-item>
        <el-form-item label='附件:'>
          <el-upload
            class="upload-demo"
            action="#"
            multiple
            ref="upload"
            :disabled="Action !== 1"
            :on-change="filechange"
            :http-request="uploadFile"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :limit="5"
            :on-exceed="handleExceed"
            :file-list="fileList">
            <el-button size="small" type="primary" :disabled="Action !== 1">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button v-show="Action === 1" type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog :close-on-press-escape=false :close-on-click-modal="false" title="网络图片" :visible.sync="imgdialog" v-el-drag-dialog width="500px">
      <el-select v-model="webImgurl" style="width:100%;margin-bottom: 10px;">
        <el-option v-for="(item, index) in webImgList" :key="index" :value="item.URL" :label="item.Descp"></el-option>
      </el-select>
      <img :src="webImgurl" style="width:100%"  :alt="webImgurl">
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="choseImg()">确 定</el-button>
        <el-button type="info" @click="imgdialog = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog :close-on-press-escape=false :close-on-click-modal="false" title="分隔符" :visible.sync="delimiterDialog" v-el-drag-dialog width="500px">
      <el-select v-model="Delimiter" style="width:100%;margin-bottom: 10px;">
        <el-option value="[%datetime%]" label="日期时间"></el-option>
        <el-option value="[%date%]" label="日期"></el-option>
        <el-option value="[%time%]" label="时间"></el-option>
        <el-option value="url" label="公司网址"></el-option>
        <el-option value="[%line%]" label="随机分隔行"></el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="choseDelimiter()">确 定</el-button>
        <el-button type="info" @click="delimiterDialog = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog 
      :close-on-press-escape=false
      :visible.sync="transferdialog"
      title="请选择对象"
      v-el-drag-dialog
      :close-on-click-modal = false>
      <tree-transfer 
        :title="['待选择','已选择']"
        :from_data='acceptedUser'       
        :to_data='toData'            
        :defaultProps="{label:'DepartmentName', key:'Account'}"
        ref="myTransfer"
        filter          
        >
    </tree-transfer>
      <span slot="footer" class="dialog-footer">
        <el-button v-show="Action === 1" type="primary" @click="transfersubmit()">确 定</el-button>
        <el-button type="info" @click="transferdialog = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { PostalMime } from 'postal-mime';
import Cookies from 'js-cookie'
import treeTransfer from 'el-tree-transfer'
import { connrequest, uploadfile, downloadfile, uploadfile2 } from '@/api/firstPage'
import { parseTime, getNowDay, getuuid, getTreeData } from '@/utils/index.js';
import { getToken } from '@/utils/auth' // get token from cookie
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import EditorBar from '@/components/EditorBar'
export default {
directives: { elDragDialog },
components: { EditorBar, treeTransfer },
data() {
  return {
    pageNum: 1,
    pageSize: 10,
    total: 0,
    tableData: [],
    ToAccount: [],
    emailForm: {},
    emailList: [],
    webImgList: [],
    webImgurl: '',
    webImglink: '',
    fileList:[],
    Delimiter: '',
    delimiterDialog: false,
    dialogVisible: false,
    transferdialog: false,
    imgdialog: false,
    TaskID:'',
    acceptedUser: [],
    choseman:[],
    rules: {
      Name:[
        { required: true, message: "请选择接收对象"}
      ],
      CreateTime:[
        { required: true, message: "请选择创建时间"}
      ],
      // link:[
      //   { required: true, message: "请输入图片跳转链接"}
      // ],
      Title:[
        { required: true, message: "请输入邮件标题"}
      ]
      // Subject:[
      //   { required: true, message: "请输入邮件内容"}
      // ],
    },
    resourceForm: {},
    searchform:{},
    Action: 1,
    editorhtml:'',
    sethtml:'',
    rowIndex:'',
    fromData:[],    //源数据 类型：Array 必填：true 补充：数据格式同element-ui tree组件，但必须有id和pid],
    toData:[]    //目标数据 类型：Array 必填：true 补充：数据格式同element-ui tree组件，但必须有id和pid
  }
},
  watch:{},
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.getData()
    // this.GetCustomer()
    this.getwebImg()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
  },
  methods: {
    async refreshPage(){
      const res = await this.getData()
      if(this.rowIndex !== '' && res.length > 0){
        this.rowclick(res[this.rowIndex])
      }
    },
    async getwebImg(){
      const res = await connrequest('GetEMailResList')
      res.Data = res.Data || []
      res.Data.map(item => {
        item.CreateTime = parseTime(item.CreateTime)
        return item
      })
      this.webImgList = res.Data
    },
    aiSoftText(){
      this.$message.info('该功能开发中')
    },
    imgdialogopen(){
      this.webImgurl = ''
      this.webImglink = ''
      this.imgdialog = true
    },
    delimiter(){
      this.Delimiter = ''
      this.delimiterDialog = true
    },
    choseDelimiter(){
      if(this.Delimiter === ''){
        this.$message.error('请选择分隔符')
        return false
      }
      this.$nextTick(async ()=>{
        if(this.Delimiter == 'url'){
          const res = await connrequest('GetDCDInfo')
          this.$refs.editor.setTxT(`<a style="color:blue;border-bottom:1px solid blue" href="[%corp_url%]">${res.Data.CorpName}</a>`)
          this.delimiterDialog = false
        }else{
          this.editorhtml = this.editorhtml += this.Delimiter
          this.$refs.editor.setTxT(this.Delimiter)
          this.delimiterDialog = false
        }
      })
    },
    choseImg(){
      if(this.webImgurl === ''){
        this.$message.error('请选择图片')
        return false
      }
      this.$refs.editor.insertImg(this.webImgurl);
      this.imgdialog = false
    },
    // 穿梭框提交
    transfersubmit(){
      let arr = this.flatten(this.toData)
      arr = arr.filter(item => {return item.ParentID === undefined})
      let str = arr.map(item => {
        return `${item.Corp} / ${item.DepartmentName}` 
      })
      this.$set( this.resourceForm, 'Name', str.join(','))
      this.choseman = arr
      this.transferdialog = false
    },
    flatten (tree, arr = []) {
      tree.forEach(item => {
        const {children, ...props} = item
        // 添加除了children的属性
        arr.push(props)
        if (children) {
          // 递归将所有节点加入到结果集中
          this.flatten(children, arr)
        }
      })
      return arr
    },
    rowStyle ({ row, rowIndex }) {
      if (this.rowIndex === rowIndex) {
        return {
          'background-color': '#ffeecf !important'
        }
      }
    },
    rowClassName ({ row, rowIndex }) {
      row.index = rowIndex
    },
    changesourceCode(val){
      this.$refs.editor.sethtml(this.sethtml) 
    },
    async GetCustomer(){
      const params = {
            Paging:{
              QueryPageNo: 1,
              QueryPageLength: 1000000
            },
            Filter:{
              Account: "",
              CorpName: "",
              Name: "",
              Department: "",
              CustomType: ""
            }
          }
      const res = await connrequest('GetCustomer', params)
      const GetCustomerClass = await connrequest('GetCustomerClass')
      let arr = GetCustomerClass.Data
      res.Data = res.Data || []
      res.Data.map(item => {
        arr.push({DepartmentName: item.Name, ParentName: item.BelongGroup, Account: item.Account, Name: item.Name, Corp: item.CorpName})
      })
      arr.map(item => {
        item.id = item.id
        item.pid = item.ParentName
      })
      
      // 构建树形结构
      const tree = {};
      res.Data = res.Data || []
      res.Data.forEach(item => {
        if (!tree[item.ParentName]) {
          tree[item.ParentName] = {};
        }
        if (!tree[item.ParentName][item.DepartmentName]) {
          tree[item.ParentName][item.DepartmentName] = {};
        }
        if (!tree[item.ParentName][item.DepartmentName][item.Corp]) {
          tree[item.ParentName][item.DepartmentName][item.Corp] = [];
        }
        tree[item.ParentName][item.DepartmentName][item.Corp].push(item);
      });
      // 转换格式
      const generateRandomId = () => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(36); // 生成默认的随机ID
      const treeData = [];
      for (const department in tree) {
        const departmentNode = {
          id: generateRandomId(), // 添加随机ID
          label: department,
          children: []
        };
        for (const name in tree[department]) {
          const nameNode = {
            id: generateRandomId(), // 添加随机ID
            label: name,
            children: []
          };
          for (const imtool in tree[department][name]) {
            const accounts = tree[department][name][imtool];
            const imtoolNode = {
              id: generateRandomId(), // 添加随机ID
              label: imtool,
              children: accounts.map(account => ({
                id: generateRandomId(), // 添加随机ID
                label: account.Name
              }))
            };
            nameNode.children.push(imtoolNode);
          }
          departmentNode.children.push(nameNode);
        }
        treeData.push(departmentNode);
      }
      this.acceptedUser = getTreeData(this.treeing(arr,'DepartmentName','ParentName'))
      this.acceptedUser = this.setDisabled(this.acceptedUser)
      // this.acceptedUser = treeData
      this.acceptedUser2 = res.Data
      // this.acceptedUser = res.Data
      // console.log(this.acceptedUser,100);
      // console.log(this.acceptedUser2,100);
    },
    setDisabled(arr){
      arr.map(item => {
        if(!item.children && !item.Account){
          item.disabled = true
        }
        if(item.children){
          this.setDisabled(item.children)
        }
        return item
      })
      return arr
    },
    treeing(arr, id, parentid) {
      let tree = []
      const map = {}
      for (let item of arr) {
        // 一个新的带children的结构
        let newItem = map[item.DepartmentName] = {
          ...item,
          children: []
        }
        if (map[item.ParentName]) { // 父节点已存进map则在父节点的children添加新元素
          let parent = map[item.ParentName]
          parent.children.push(newItem)
        } else { // 没有父节点，在根节点添加父节点
          tree.push(newItem)
        }
      }
      return tree
    },
    async addResources(){
      this.Action = 1
      this.resourceForm = {...{Status: 0}}
      this.$nextTick(async ()=>{
        this.$refs['resourceForm'].clearValidate()
        this.$refs.editor.clearText()
        this.$refs.upload.clearFiles()
        this.toData = []
        await this.GetCustomer()
      })
      this.dialogVisible = true
    },
    changeMailGlobal(row){
      this.Action = 2
      let userList = row.name.split(',')
      this.resourceForm = {...row, Name: row.name}
      // this.toData = this.acceptedUser2.filter(item => {return userList[0].includes(item.Name)})
      if(row.Attachlength > 0){
          row.Attach.map(item => {
          item.name = item.FileName
          return item
        })
      }
      this.fileList = row.Attach
      this.dialogVisible = true
      this.$nextTick(()=>{
        this.editorhtml = row.Subject
        this.$refs.editor.updateText()
        // this.$refs.upload.clearFiles()
      })
    },
    deleteMailGlobal(row){
      this.Action = 3
      this.resourceForm = {...row}
      this.$confirm('此操作将删除该任务, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const data = {
          Data:{
            Action: this.Action,
            Detail: {
              ...this.resourceForm
            }
          }
        }
        const res = await connrequest('EditEMailTaskNotify', data)
        if(res.Status.StatusCode === 0){
          this.$message.success('删除成功')
          this.dialogVisible = false
          this.getData()
          this.ToAccount = []
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    async getData() {
      const data = {
        Paging:{
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || ''
        }
      }
      const res = await connrequest('GetEMailTaskNotify', data)
      res.Data = res.Data || []
      res.Data.map(item => { 
        let time = item.EndTime - item.StartTime
        let d = Math.floor(time / 3600 / 24);
        let h = Math.floor((time  % 86400) / 3600);
        var m = Math.floor(((time % 86400) % 3600) / 60);
        var s = Math.floor(((time % 86400) % 3600) % 60);
        time = `${d < 1 ? '' : d + '天'} ${h < 1 ? '' : h + '小时'} ${m < 1 ? '' : m + '分钟'} ${s}秒` ;
        item.CreateTime = parseTime(item.CreateTime)
        item.StartTime = item.ExecStatus === 1 ? `${time} （${parseTime(item.StartTime)} ~ ${parseTime(item.EndTime)}）` : '--'
        let obj = { success: 0, danger: 0,  info: 0, read: 0}
        let success = 0
        let danger = 0
        let info = 0
        let read = 0
        item.name = []
        item.ToAccount.map(newitem => {
          obj[item.ExecStatus] = obj[item.ExecStatus] + 1
          item.name.push(newitem.Name)
          if(newitem.ExecStatus === 1){
            success++
          }
          else if(newitem.ExecStatus === 2){
            danger++
          }else if(newitem.ExecStatus === 0){
            info++
          }else if(newitem.ExecStatus === 3){
            read++
          }
        })
        item.obj = obj
        item.success = success
        item.danger = danger
        item.info = info
        item.read = read
        item.name = item.name.join('，')
        item.Subject = Buffer.from(item.Subject, 'base64').toString('utf8')
        item.Title = Buffer.from(item.Title, 'base64').toString('utf8')
        item.Attachlength = item.Attach?.length || 0
        return item
      })
      this.tableData = res.Data
      this.total = res.Paging?.TotalCount || 0
      return res.Data
    },
    rowclick(row){
      this.rowIndex = row.index
      row.ToAccount.map(item => {
        item.StatusChangeTime = parseTime(item.StatusChangeTime)
        item.RcvArea = item.RcvArea ? item.RcvArea.replace(/\s+/g, "") : '';
        // item.RcvIP = `${RcvArea}(${RcvIP})`
        return item
      })
      this.ToAccount = row.ToAccount
      this.TaskID = row.TaskID
    },
    editorchange(val){
      this.editorhtml = val
      this.sethtml = val
    },
    submit(){
      if(this.editorhtml === ''){
        this.$message.error('请输入邮件内容')
        return false
      }
      let html = `
      <!doctype html>
      <html lang="en">
      <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
      </head>
      <body>
        ${this.editorhtml}
      </body>
      <style>
        *{
          margin: 0
          padding: 0
        }
        img{
          vertical-align:left;
          display:block;
        }
      </style>
      </html>`

      // var eleLink = document.createElement('a');
      // eleLink.download = 'filename.html';
      // eleLink.style.display = 'none';
      // // 字符内容转变成blob地址
      // var blob = new Blob([html]);
      // eleLink.href = URL.createObjectURL(blob);
      // // 触发点击
      // document.body.appendChild(eleLink);
      // eleLink.click();
      // // 然后移除
      // document.body.removeChild(eleLink);
      // return false

      
      this.$refs['resourceForm'].validate(async (valid) => {
        if(valid){
          let ToAccount = []
          this.choseman.map(item => {
            ToAccount.push({ Name: `${item.Corp} / ${item.Name}`, Account: item.Account, ExecStatus: 0 })
          })
          const data = {
            Data:{
              Action: this.Action,
              Detail: {
                StartTime: 0,
                EndTime: 0,
                ExecStatus: 0,
                TaskID: this.resourceForm.TaskID || getuuid(),
                CreateTime: new Date().getTime(),
                Title: Buffer.from(this.resourceForm.Title, 'utf-8').toString('base64'),
                ToAccount: ToAccount,
                Attach:this.Attach,
                Subject: Buffer.from(html, 'utf-8').toString('base64')
              }
            }
          }
          // console.log(data);
          // return false;
          const res = await connrequest('EditEMailTaskNotify', data)
          if(res.Status.StatusCode === 0){
            this.Action === 1 ? this.$message.success('添加成功') : this.$message.success('修改成功')
            this.dialogVisible = false
            this.getData()
            this.ToAccount = []
          }
        }
      })
    },
    async uploadFile(file){
      let formData = new FormData();
      formData.append('CmdCode', "UploadEMailAttatch");
      formData.append('FileName', file.file.name);
      formData.append('InnerName', file.file.uid);
      formData.append('file', file.file);
      formData.append('Token', getToken());
      const res = await uploadfile('UploadEMailAttatch',formData)
      if(res.Status.StatusCode === 0) {
        this.$message.success('文件上传成功')
      }
    },
    // async uploadFile(file){
    //   console.log(file.file)
    //   let data = {
    //     Data:{
    //       FileName: file.file.name,
    //       InnerName: file.file.uid + '',
    //       file: file.file
    //     }
    //   }
    //   const res = await uploadfile2('UploadEMailAttatch', data)
    //   if(res.Status.StatusCode === 0) {
    //     this.$message.success('文件上传成功')
    //   }
    // },
    
    filechange(file, fileList){
      let arr = []
      fileList.map(item => {
        arr.push({FileName: item.name, InnerName: item.uid + ''})
      })
      this.Attach = arr
    },
    fileclick(){
      this.$refs.filetemplete.click()
    },
    filetempleteChange(e){
      let file = e.target.files[0]
      if(file.name.indexOf("html") < 0 && file.name.indexOf("txt") < 0){
        this.$message.error('请选择html格式或txt格式的文件')
        this.$refs.filetemplete.value = ''
        return false
      }
      // FileReader对象，h5提供的异步api，可以读取文件中的数据。
      const reader = new FileReader()
      // readAsText是个异步操作，只有等到onload时才能显示数据。
      reader.readAsText(file)
      reader.onload = () => {
        //当读取完成后回调这个函数,然后此时文件的内容存储到了result中
        this.sethtml = reader.result
        this.$refs.editor.sethtml(this.sethtml)
        this.$refs.filetemplete.value = ''
      }
    },
    async handleRemove(file, fileList) {
      const data = {
        Data:{
          InnerName: file.uid
        }
      }
      const res = await connrequest('DeleteEMailAttach', data)
      if(res.Status.StatusCode === 0){
        this.$message.success('文件删除成功')
      }
    },
    async handlePreview(file) {
      // const data = {
      //   Data:{
      //     FileName: file.InnerName
      //   }
      // }
      // const res = await downloadfile('DownloadPublicFile', data)
      // let blobUrl = window.URL.createObjectURL(new Blob([res]));
      // const a = document.createElement('a');
      // a.style.display = 'none';
      // a.download = file.InnerName;
      // a.href = blobUrl;
      // a.click();
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    handleSizeChange(val){
      this.pageNum = 1
      this.pageSize = val
      this.getData()
    },
    handleCurrentChange( pageNum ){
      this.pageNum = pageNum
      this.getData()
    },
    search(val) {
      this.pageNum = 1
      this.searchform = {...val}
      this.getData()
    },
    reset() {
      let endTime = new Date(new Date().setHours(0, 0, 0, 0))
      let startTime = endTime - (Cookies.get('DefaultLogDays') * 1 * 3600 * 24 * 1000);
      let arr = [ parseTime(startTime), '']
      this.pageNum = 1
      this.formOptions = this.formOptions.map( item => {
        if(item.label === "日期"){
          item.initValue = arr
        }else{
          item.initValue = ""
        }
        return item
      })
      this.searchform = {}
      this.$set(this.searchform,'timeRange', arr)
      this.$refs.connsearch.addInitValue()
      this.getData()
    }
  }
}
</script>
<style lang="scss" scoped>
/* @import url(); 引入css类 */
@import "~@/styles/variables.scss";
::v-deep .wl-transfer .transfer-title{
  font-size: 14px !important;
  margin: 0px !important;
}
.content {
  position: relative;
  margin-top: 25px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  ::v-deep .certification{
    .el-form-item{
      margin-bottom: 10px;
    }
    .el-col{
      display: flex;
      align-items: center;
      p{
        width: 100px;
        display:block;
        color: #aaa;
        font-size: 12px;
        padding-left: 20px;
        white-space: nowrap;
      }
    }
  }
}
.top{
  flex-wrap: nowrap;
  margin-bottom: 20px;
}
.btn{
  margin: 20px 0;
}
::v-deep .tabs{
  .el-tabs__content{
    overflow: visible !important;
  }
}
::v-deep .tableRowclcick .el-table__body tr:hover>td{
  background-color: #ffeecf!important;
}
::v-deep .tableRowclcick .el-table__body tr.current-row>td{
  background-color: #ffeecf!important;
}



</style>

